package middleware

import "net/http"

type UserCorsMiddleware struct {
	AllowOrigin      string
	AllowHeaders     string
	AllowMethods     string
	ExposeHeaders    string
	AllowCredentials bool
}

func NewUserCorsMiddleware(allowOrigin, allowHeaders, allowMethods, exposeHeaders string, allowCredentials bool) *UserCorsMiddleware {
	return &UserCorsMiddleware{
		AllowOrigin:      allowOrigin,
		AllowHeaders:     allowHeaders,
		AllowMethods:     allowMethods,
		ExposeHeaders:    exposeHeaders,
		AllowCredentials: allowCredentials,
	}
}

func (m *UserCorsMiddleware) Handle(next http.HandlerFunc) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		m.setHeader(w)
		if r.Method == http.MethodOptions {
			w.WriteHeader(http.StatusNoContent)
			return
		}
		next(w, r)
	}
}

// setHeader 设置响应头
func (m *UserCorsMiddleware) setHeader(w http.ResponseWriter) {
	w.Header().Set("Access-Control-Allow-Origin", m.AllowOrigin)
	w.Header().Set("Access-Control-Allow-Headers", m.AllowHeaders)
	w.Header().Set("Access-Control-Allow-Methods", m.AllowMethods)
	w.Header().Set("Access-Control-Expose-Headers", m.ExposeHeaders)
	if m.AllowCredentials {
		w.Header().Set("Access-Control-Allow-Credentials", "true")
	}
}
